package com.example.springboot.config.applicationContextNameAware;

import com.sun.istack.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 上下文的持有者
 * 用于一些工具类中，对象的获取
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/12 9:59
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 将容器上下文注入
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 自定义bean方法，的到bean
     *
     * @return
     */
    public static Object getBean(String beanName, @NotNull Class clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        T bean = applicationContext.getBean(clazz);
        return bean;
    }
}
